package com.weasel.helper;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;


/**
 * Created by Dylan on 2015/12/18.
 */
public final class DESHelper {

    private static Key key;
    private static String KEY_STR="mykey";

    static{
        try{
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            SecureRandom secureRandom= SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY_STR.getBytes());
            generator.init(secureRandom);
            key = generator.generateKey();
            generator=null;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public static String encrypt(String value){
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try{
            byte[] strBytes = value.getBytes("UTF-8");
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            return base64Encoder.encode(encryptStrBytes);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public static String decrypt(String value){
        BASE64Decoder base64Decoder = new BASE64Decoder();
        try{
            byte[] strBytes = base64Decoder.decodeBuffer(value);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            return new String(encryptStrBytes,"UTF-8");
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    protected DESHelper(){}
}
